package com.rookie.jeesdp.iteceptor;

import com.rookie.jeesdp.annotation.CheckPermissions;
import com.rookie.jeesdp.utils.UserUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CheckPermissionsInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod methodHandler = (HandlerMethod) handler;
        CheckPermissions permissions = methodHandler.getMethodAnnotation(CheckPermissions.class);
        if (permissions == null || permissions.value().isEmpty()) {
            return true;
        } else {
            if (UserUtils.hasPermission(permissions.value())) {
                return true;
            } else {
                response.setStatus(HttpStatus.FORBIDDEN.value());
                return false;
            }
        }
    }
}
